package ti.ml.car.ui;

import java.awt.Dimension;
import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.util.Observable;
import java.util.Observer;
import javax.swing.JOptionPane;
import ti.ml.car.Map;
import ti.ml.car.Route;
import ti.ml.car.domain.Controller;

/**
 *
 * @author robin
 */
public class MainForm extends javax.swing.JFrame implements Observer {

    /**
     * Creates new form MainForm
     */
    private Controller c;

    public MainForm() {
        c = Controller.getIntance();
        c.addObserver(this);
        initComponents();
        //btnPanel
        panelControls.setSize(150, 1280);

        //logPanel
        panelLog.setSize(480, 800);
        txtLog.setText(panelLog.getSize().height + " " + panelLog.getSize().width);

        //mapPanel
        panelMap.setSize(800, 800);

        //keyevents

        KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() {
            @Override
            public boolean dispatchKeyEvent(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_UP) {
                    btnUpActionPerformed(null);
                }
                if (e.getKeyCode() == KeyEvent.VK_DOWN) {
                    btnDownActionPerformed(null);
                }
                if (e.getKeyCode() == KeyEvent.VK_LEFT) {
                    btnLeftActionPerformed(null);
                }
                if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
                    btnRightActionPerformed(null);
                }
                return false;
            }
        });

        //properties
        setTitle("Onderzoeksproject - Pathfinding, Autonomous driving car simulator");

        System.setProperty("apple.laf.useScreenMenuBar", "true");
        Toolkit tk = Toolkit.getDefaultToolkit();

        Dimension screenSize = tk.getScreenSize();
        int screenWidth = screenSize.width;
        int screenHeight = screenSize.height;

        setLocation((screenWidth - 1280) / 2, (screenHeight - 900) / 2 / 2);
        setSize(1280, 921);
    }

    public String getTxtLog() {
        return txtLog.getText();
    }

    public void setTxtLog(String txt) {
        txtLog.setText(txt);
    }

    public void appendTxtLog(String txt) {
        txtLog.append(txt);
        txtLog.selectAll();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        panelLog = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        txtLog = new javax.swing.JTextArea();
        panelMap = new javax.swing.JPanel();
        panelControls = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        btnRight = new javax.swing.JButton();
        btnDown = new javax.swing.JButton();
        btnLeft = new javax.swing.JButton();
        btnUp = new javax.swing.JButton();
        btnReset = new javax.swing.JButton();
        btnStart = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        txtTarget = new javax.swing.JTextField();
        btnResetAStar = new javax.swing.JButton();
        btnStartAStar = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setPreferredSize(new java.awt.Dimension(1280, 800));
        setResizable(false);

        panelLog.setBackground(new java.awt.Color(204, 204, 204));
        panelLog.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        panelLog.setPreferredSize(new java.awt.Dimension(480, 800));

        txtLog.setEditable(false);
        txtLog.setBackground(new java.awt.Color(0, 0, 0));
        txtLog.setColumns(20);
        txtLog.setFont(new java.awt.Font("Lucida Grande", 1, 12)); // NOI18N
        txtLog.setForeground(new java.awt.Color(255, 255, 255));
        txtLog.setRows(5);
        jScrollPane1.setViewportView(txtLog);

        org.jdesktop.layout.GroupLayout panelLogLayout = new org.jdesktop.layout.GroupLayout(panelLog);
        panelLog.setLayout(panelLogLayout);
        panelLogLayout.setHorizontalGroup(
            panelLogLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 478, Short.MAX_VALUE)
        );
        panelLogLayout.setVerticalGroup(
            panelLogLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 627, Short.MAX_VALUE)
        );

        getContentPane().add(panelLog, java.awt.BorderLayout.WEST);

        panelMap=new Map();
        panelMap.setBackground(new java.awt.Color(255, 255, 255));
        panelMap.setPreferredSize(new java.awt.Dimension(800, 800));

        org.jdesktop.layout.GroupLayout panelMapLayout = new org.jdesktop.layout.GroupLayout(panelMap);
        panelMap.setLayout(panelMapLayout);
        panelMapLayout.setHorizontalGroup(
            panelMapLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 522, Short.MAX_VALUE)
        );
        panelMapLayout.setVerticalGroup(
            panelMapLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 629, Short.MAX_VALUE)
        );

        getContentPane().add(panelMap, java.awt.BorderLayout.CENTER);

        panelControls.setBackground(new java.awt.Color(204, 204, 204));
        panelControls.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        panelControls.setPreferredSize(new java.awt.Dimension(786, 100));

        jLabel1.setText("Dijkstra");

        btnRight.setText("Right");
        btnRight.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRightActionPerformed(evt);
            }
        });

        btnDown.setText("Down");
        btnDown.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDownActionPerformed(evt);
            }
        });

        btnLeft.setText("Left");
        btnLeft.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLeftActionPerformed(evt);
            }
        });

        btnUp.setText("Up");
        btnUp.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnUpActionPerformed(evt);
            }
        });

        btnReset.setText("reset");
        btnReset.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnResetActionPerformed(evt);
            }
        });

        btnStart.setText("Start");
        btnStart.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnStartActionPerformed(evt);
            }
        });

        jLabel2.setText("Bestemming:");

        txtTarget.setColumns(3);
        txtTarget.setText("339");
        txtTarget.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtTargetKeyPressed(evt);
            }
        });

        btnResetAStar.setText("reset");
        btnResetAStar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnResetAStarActionPerformed(evt);
            }
        });

        btnStartAStar.setText("Start");
        btnStartAStar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnStartAStarActionPerformed(evt);
            }
        });

        jLabel4.setText("A*");

        org.jdesktop.layout.GroupLayout panelControlsLayout = new org.jdesktop.layout.GroupLayout(panelControls);
        panelControls.setLayout(panelControlsLayout);
        panelControlsLayout.setHorizontalGroup(
            panelControlsLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(panelControlsLayout.createSequentialGroup()
                .add(panelControlsLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(panelControlsLayout.createSequentialGroup()
                        .addContainerGap()
                        .add(panelControlsLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                            .add(panelControlsLayout.createSequentialGroup()
                                .add(btnStart)
                                .add(1, 1, 1)
                                .add(btnReset))
                            .add(panelControlsLayout.createSequentialGroup()
                                .add(jLabel2)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                .add(txtTarget, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))))
                    .add(panelControlsLayout.createSequentialGroup()
                        .add(58, 58, 58)
                        .add(jLabel1)))
                .add(29, 29, 29)
                .add(panelControlsLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(panelControlsLayout.createSequentialGroup()
                        .add(btnStartAStar)
                        .add(1, 1, 1)
                        .add(btnResetAStar))
                    .add(panelControlsLayout.createSequentialGroup()
                        .add(52, 52, 52)
                        .add(jLabel4)))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 413, Short.MAX_VALUE)
                .add(btnLeft)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(panelControlsLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                    .add(btnUp, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(btnDown))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(btnRight)
                .addContainerGap())
        );
        panelControlsLayout.setVerticalGroup(
            panelControlsLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(panelControlsLayout.createSequentialGroup()
                .addContainerGap()
                .add(panelControlsLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(panelControlsLayout.createSequentialGroup()
                        .add(btnUp)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(panelControlsLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(btnRight)
                            .add(btnDown)
                            .add(btnLeft)))
                    .add(panelControlsLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                        .add(panelControlsLayout.createSequentialGroup()
                            .add(jLabel4)
                            .add(28, 28, 28)
                            .add(panelControlsLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                                .add(btnResetAStar)
                                .add(btnStartAStar)))
                        .add(panelControlsLayout.createSequentialGroup()
                            .add(jLabel1)
                            .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                            .add(panelControlsLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                .add(jLabel2)
                                .add(txtTarget, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 16, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                            .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                            .add(panelControlsLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                                .add(btnReset)
                                .add(btnStart)))))
                .add(22, 22, Short.MAX_VALUE))
        );

        getContentPane().add(panelControls, java.awt.BorderLayout.NORTH);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnLeftActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLeftActionPerformed
        // TODO add your handling code here:
        ((Map) panelMap).getCar().moveLeft();
    }//GEN-LAST:event_btnLeftActionPerformed

    private void btnRightActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRightActionPerformed
        // TODO add your handling code here:
        ((Map) panelMap).getCar().moveRight();
    }//GEN-LAST:event_btnRightActionPerformed

    private void btnUpActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnUpActionPerformed
        // TODO add your handling code here:
        ((Map) panelMap).getCar().moveUp();

    }//GEN-LAST:event_btnUpActionPerformed

    private void btnDownActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDownActionPerformed
        // TODO add your handling code here:
        ((Map) panelMap).getCar().moveDown();
    }//GEN-LAST:event_btnDownActionPerformed

    private void btnResetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnResetActionPerformed
        // TODO add your handling code here:
        ((Map) panelMap).getCar().resetPosition();
        ((Map) panelMap).resetMap();
    }//GEN-LAST:event_btnResetActionPerformed

    private void btnStartActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnStartActionPerformed
        int target = Integer.parseInt(txtTarget.getText());
        ((Map) panelMap).followRoute(target);
    }//GEN-LAST:event_btnStartActionPerformed

    private void txtTargetKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtTargetKeyPressed
        // TODO add your handling code here:
        if(evt.getKeyCode()==KeyEvent.VK_ENTER){
            appendTxtLog("\nenter pressed in target");
            ((Map)panelMap).resetMap();
            ((Map)panelMap).getRoad().getScreenData()[Integer.parseInt(txtTarget.getText())][4]=3;
            
        }
    }//GEN-LAST:event_txtTargetKeyPressed

    private void btnResetAStarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnResetAStarActionPerformed
        // TODO add your handling code here:
        ((Map) panelMap).getCar().resetPosition();
        ((Map) panelMap).resetMap();
    }//GEN-LAST:event_btnResetAStarActionPerformed

    private void btnStartAStarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnStartAStarActionPerformed
        // TODO add your handling code here:
        int target=Integer.parseInt(txtTarget.getText());
        ((Map)panelMap).followAStarRoute(target);
    }//GEN-LAST:event_btnStartAStarActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MainForm().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnDown;
    private javax.swing.JButton btnLeft;
    private javax.swing.JButton btnReset;
    private javax.swing.JButton btnResetAStar;
    private javax.swing.JButton btnRight;
    private javax.swing.JButton btnStart;
    private javax.swing.JButton btnStartAStar;
    private javax.swing.JButton btnUp;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JPanel panelControls;
    private javax.swing.JPanel panelLog;
    private javax.swing.JPanel panelMap;
    private javax.swing.JTextArea txtLog;
    private javax.swing.JTextField txtTarget;
    // End of variables declaration//GEN-END:variables

    @Override
    public void update(Observable o, Object arg) {
        if (((String) arg).equals("appendLog")) {
            appendTxtLog(c.offerTxtLog());
        }
        if (((String) arg).equals("endOfRoute")) {
            JOptionPane.showMessageDialog(null, c.offerTxtLog());
            btnResetActionPerformed(null);
        }
    }
}
